TARGETS := sort sort_p sort_b

###################################
# No need to edit below this line #
###################################

TARGETS32 := $(TARGETS:%=%.32)
TARGETS64 := $(TARGETS:%=%.64)

ifeq ($(shell uname -m),i686) 
        ALLTARGETS := $(TARGETS32)
else
        ALLTARGETS := $(TARGETS64)
endif

CC := icc
CFLAGS := -g -Wall
LDFLAGS := -lrt -lm
COMMON_SRC := tests.c main.c ktiming.c util.c sort_i.c sort_p.c sort_b.c sort_c.c isort.c sort_m.c sort_f.c
TEST_SRC_P := test_sort_p.c ktiming.c util.c sort_p.c
TEST_SRC_B := test_sort_b.c ktiming.c util.c sort_b.c
COMMON_HEADERS := ktiming.h util.h

OLDMODE := $(shell cat .buildmode 2> /dev/null)
ifeq ($(DEBUG),1)
CFLAGS := -DDEBUG -O0 $(CFLAGS)
ifneq ($(OLDMODE),debug)
$(shell echo debug > .buildmode)
endif
else
CFLAGS := -O1 -DNDEBUG $(CFLAGS)
ifneq ($(OLDMODE),nodebug)
$(shell echo nodebug > .buildmode)
endif
endif

# make all targets specified
all: $(ALLTARGETS)

# pattern rule for building 32-bit targets
%.32: %.c $(COMMON_SRC) $(COMMON_HEADERS) .buildmode
	$(CC) $(CFLAGS) -m32 -msse3 $< $(COMMON_SRC) $(LDFLAGS) -o $@

# pattern rule for building 64-bit targets
%.64: %.c $(COMMON_SRC) $(COMMON_HEADERS) .buildmode
	$(CC) $(CFLAGS) -m64 $< $(COMMON_SRC) $(LDFLAGS) -o $@

# pattern rule for building 32-bit targets for sort_p
sort_p.32: $(TEST_SRC_P) $(COMMON_HEADERS) .buildmode
	$(CC) $(CFLAGS) -m32 -msse3 $(TEST_SRC_P) $(LDFLAGS) -o $@

# pattern rule for building 64-bit targets for sort_p
sort_p.64: $(TEST_SRC_P) $(COMMON_HEADERS) .buildmode
	$(CC) $(CFLAGS) -m64 $(TEST_SRC_P) $(LDFLAGS) -o $@

# pattern rule for building 32-bit targets for sort_b
sort_b.32: $(TEST_SRC_B) $(COMMON_HEADERS) .buildmode
	$(CC) $(CFLAGS) -m32 -msse3 $(TEST_SRC_B) $(LDFLAGS) -o $@

# pattern rule for building 64-bit targets for sort_b
sort_b.64: $(TEST_SRC_B) $(COMMON_HEADERS) .buildmode
	$(CC) $(CFLAGS) -m64 $(TEST_SRC_B) $(LDFLAGS) -o $@

# run each of the targets on inputs 2047, 2048, and 2049
run: $(ALLTARGETS)
	for X in $(ALLTARGETS) ; do \
		echo $$X ; \
		./$$X 2047 10000; \
		./$$X 2048 10000; \
		./$$X 2049 10000; \
		echo ; \
	done

# remove targets as well as output generated by PNQ
clean:
	rm -f $(ALLTARGETS) *.std*
